/*
 * Copyright (c) 2012 Jonathan Tyers
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package uk.org.uplink.guicemodulescanner.reflections;

import static com.google.common.base.Preconditions.checkArgument;

import java.util.LinkedHashSet;
import java.util.Set;

import org.reflections.Reflections;

import uk.org.uplink.guicemodulescanner.AutoloadModule;
import uk.org.uplink.guicemodulescanner.SimpleReflectionInstanceCreator;

import com.google.inject.Module;

/**
 * Provides module scanning using the Reflections library.
 * 
 * @author jonny
 */
public class ReflectionsModuleScanner {
	private final Reflections reflections;

	private final SimpleReflectionInstanceCreator instanceCreator;

	public ReflectionsModuleScanner(final Reflections reflections, final SimpleReflectionInstanceCreator instanceCreator) {
		super();
		this.reflections = reflections;
		this.instanceCreator = instanceCreator;
	}

	@SuppressWarnings("unchecked")
	public Set<Module> scanForModules() {
		Set<Module> result = new LinkedHashSet<Module>();

		Set<Class<?>> moduleClasses = reflections.getTypesAnnotatedWith(AutoloadModule.class);
		for (Class<?> moduleClass : moduleClasses) {
			checkArgument(Module.class.isAssignableFrom(moduleClass),
					"Class %s is annotated with @AutoloadModule but does not implement the Guice Module interface",
					moduleClass.getCanonicalName());

			Module instance = instanceCreator.createInstance((Class<? extends Module>) moduleClass);
			result.add(instance);
		}

		return result;
	}
}
